package com.zhf.filter;

import com.zhf.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginFilter", urlPatterns = {"/header.jsp", "/index.jsp", "/Classindex.jsp"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        HttpSession session = servletRequest1.getSession();
        User user = (User) session.getAttribute("user");
        String servletPath = servletRequest1.getServletPath();
        String userName = null;
        if(user != null && servletPath.contains("login")){
            filterChain.doFilter(servletRequest, servletResponse);
        }
        else{
            // 若没有登录，则查询Cookie信息中是否已经保存账号和密码信息
            Cookie[] cookies = servletRequest1.getCookies();
            if(cookies != null && cookies.length > 0){
                for(Cookie cookie : cookies){
                    String name = cookie.getName();
                    if("userName".equals(name)){
                        userName = name;
                        break;
                    }
                }
            }
        }
        if(null != userName){
            filterChain.doFilter(servletRequest, servletResponse);
        }
        else{
            servletRequest1.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
